﻿using UnityEngine;

[CreateAssetMenu(menuName = "PluggableAI/Actions/Patrol")]
public class PatrolAction : Action {

    private float _interval = 3f;
    private float _intervalPass = 0;
    private float _moveFactor = 0.5f;

    private System.DateTime _lastCheckTargetTime;

    public override void Act(StateController controller)
    {
        Patrol(controller);
    }

    private void Patrol(StateController controller)
    {
        _intervalPass += Time.deltaTime;

        RaycastHit hit;
        float lookRange = 5;
        float lookBoxCastRadius = .6f;

        Quaternion q1 = Quaternion.Euler(0, 90, 0);
        Quaternion q2 = Quaternion.Euler(0, -90, 0);
        Vector3 dirRight = q1 * controller.eyes.forward;
        Vector3 dirLeft = q2 * controller.eyes.forward;

        Debug.DrawRay(controller.eyes.position, dirRight * lookRange, Color.blue);
        Debug.DrawRay(controller.eyes.position, dirLeft * lookRange, Color.green);

        System.DateTime curTime = System.DateTime.Now;

        //太频繁地检测附近目标，若目标处于近距离的东北与西北夹角的位置会转个不停
        //也会导致敌人紧紧地跟随,很难甩掉
        if ((curTime - _lastCheckTargetTime).TotalSeconds > 1.5f)
        {
            if ((Physics.SphereCast(controller.eyes.position, lookBoxCastRadius, dirRight, out hit, lookRange)
                || Physics.Raycast(controller.eyes.position, dirRight, out hit, lookRange))
            && (hit.collider.CompareTag("Player") || hit.collider.CompareTag("Headquarters")))
            {
                controller.joyStick.TurnCoarseDirClockWise();
                Debug.DrawRay(hit.point, Vector3.up * 2, Color.blue);
                _lastCheckTargetTime = curTime;
                //_intervalPass = 0;
            }
            else if ((Physics.SphereCast(controller.eyes.position, lookBoxCastRadius, dirLeft, out hit, lookRange)
                      || Physics.Raycast(controller.eyes.position, dirLeft, out hit, lookRange))
                && (hit.collider.CompareTag("Player") || hit.collider.CompareTag("Headquarters")))
            {
                controller.joyStick.TurnCoarseDirAnticClockWise();
                Debug.DrawRay(hit.point, Vector3.up * 2, Color.green);
                _lastCheckTargetTime = curTime;
                //_intervalPass = 0;
            }
        }
       
        if (_intervalPass>=_interval)
        {
            Vector3[] dirs = new Vector3[] {
                Vector3.forward,
                Vector3.back,
                Vector3.left,
                Vector3.right,
                Vector3.back};//使得back的可能性更大

            int randomDir = Random.Range(0, dirs.Length);

            controller.joyStick.coarseDirection = dirs[randomDir];

            _intervalPass = 0;
        }else
        {
            controller.joyStick.inputMoveVal = 1;
        }
    }

}
